<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\StatusAction;
use App\Models\Base\Regional;
use App\Models\Base\ServerList;
use App\Service\RequestService;
use App\Service\ScriptService;
use App\Service\ServerOnlineService;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;

/**
 * 服务器管理.
 */
class ServerController extends Controller
{
    use ModelForm;

    /**
     * [index 区服列表].
     *
     * @Author   王文凡
     * @DateTime 2018-03-08
     *
     * @version  1.0
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('game.server_manger'));
            $content->description(trans('admin.list'));
            $content->row(function (Row $row) {
                $row->column(6, function (Column $column) {
                    $column->append(view('admin.tools.port'));
                });
            });

            $content->body($this->grid()->render());
        });
    }

    /**
     * [grid 列表视图].
     *
     * @Author   王文凡
     * @DateTime 2018-03-08
     *
     * @version  1.0
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = Admin::grid(ServerList::class, function (Grid $grid) {
            $grid->model()->withTrashed();
            $grid->server_id(trans('game.server_id'))->sortable();
            $grid->name(trans('game.name'));
            $grid->merge_tag(trans('game.merge_tag'))->display(function ($tag) {
                return $tag ?? trans('game.no');
            });

            $grid->type(trans('game.type'))->display(function ($type) {
                return $type ? "<span class='label bg-green'>".trans('game.physics_server')."</span>" : "<span class='label bg-yellow'>".trans('game.logic_server')."</span>";
            });
            $grid->region()->name(trans('game.region_name'));
            $grid->ip('ip');
            $grid->port(trans('game.port'));
            $grid->status(trans('game.status'))->display(function ($status) {
                $state = config('game.state');
                switch ($status) {
                    case "{$state[0]}":
                        return "<span class='label bg-green'>".trans('game.normal')."</span>";
                        break;
                    case "{$state[3]}":
                        return "<span class='label bg-red'>".trans('game.close')."</span>";
                        break;
                    case "{$state[5]}":
                        return "<span class='label bg-blue'>".trans('game.test')."</span>";
                }
            });
            $grid->created_at(trans('game.open_server_time'));
            $grid->filter(function ($filter) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->equal('server_id', trans('game.server_id'));
                $filter->equal('type', trans('game.type'))->select([trans('game.logic_server'), trans('game.physics_server')]);
            });

            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->add(trans('game.normal'), new StatusAction(0));
                    $batch->add(trans('game.test'), new StatusAction(10000));
                    $batch->add(trans('game.edit_port'), new StatusAction());
                });
            });
        });

        return $grid;
    }

    /**
     * [create 添加服务器].
     *
     * @Author   王文凡
     * @DateTime 2018-03-08
     *
     * @version  1.0
     *
     * @return [type] [description]
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('game.server_manger'));
            $content->description(trans('admin.new'));
            $content->body($this->form());
        });
    }

    /**
     * [form 表单].
     *
     * @Author   王文凡
     * @DateTime 2018-03-08
     *
     * @version  1.0
     *
     * @return [type] [description]
     */
    protected function form()
    {
        return Admin::form(ServerList::class, function (Form $form) {
            //当前最新服务器数据
            $one = ServerList::orderBy('server_id', 'desc')->first();
            //设置默认值
            $old_server_id = $one ? $one->server_id + 1 : 1;
            $old_port = $one ? $one->port + 1 : 6601;

            $form->text('server_id', trans('game.server_id'))->default($old_server_id)->rules('required|min:1|numeric');
            $form->text('port', trans('game.port'))->default($old_port)->rules('required');
            $form->text('name', trans('game.server_name'))->default('双线'.$old_server_id.'服')->rules('required');
            $form->select('reg_id', trans('game.region_name'))->options(Regional::all()->pluck('name', 'id'))->rules('required');
            $form->text('desc', trans('game.desc'));
            $form->ip('ip', 'ip')->default(config('game.server_ip'))->rules('ip')->help('默认游戏服ip');
            $form->saving(function (Form $form) {
                $form->model()->status = config('game.state')[5];
                //发送给服务器
                $method = request()->method();

                if ('POST' == $method) {
                    $ret = $this->SendaddServerMsg();
                    if (false == $ret) {
                        return back()->withInput(admin_toastr(trans('game.gs_communication_failed'), 'error'));
                    }
                    //执行开服脚本
                    $this->exeOpen();
                } elseif ('PUT' == $method) {
                    //修改服务器名大区名
                    $this->updateServerName();
                }
            });
        });
    }

    /**
     * [updateServerName 修改服务器名或大区名].
     *
     * @Author   王文凡
     * @DateTime 2018-05-03
     *
     * @version  1.0
     *
     * @return [type] [description]
     */
    protected function updateServerName()
    {
        $server_id = Input::post('server_id');
        $reg_id = Input::post('reg_id');
        $name = Input::post('name');
        $info = ServerList::where('server_id', $server_id)->first();
        if ($info->reg_id != $reg_id) {
            //修改大区名
            $reg = Regional::find($reg_id);
            $op = '15;'.$reg->name;
            RequestService::sendVip($op, $server_id);
        }
        if ($info->name != $name) {
            //修改服务器名
            $op = '16;'.$name;
            RequestService::sendVip($op, $server_id);
        }
    }

    /**
     * [exeOpen 执行开服].
     *
     * @Author   王文凡
     * @DateTime 2018-03-24
     *
     * @version  1.0
     */
    protected function exeOpen()
    {
        if (Input::get('ip') == config('game.server_ip')) {
            //本机开服
            ScriptService::openServer(Input::get('server_id'), Input::get('port'));
        } else {
            //跨机开服
        }
    }

    /**
     * [SendaddServerMsg 向游戏服发送开服消息].
     *
     * @Author   王文凡
     * @DateTime 2018-03-08
     *
     * @version  1.0
     */
    protected function SendaddServerMsg()
    {
        $ret = RequestService::sendAddMsg($this->combinData());

        return $ret;
    }

    /**
     * [combinData 拼装数据].
     *
     * @Author   王文凡
     * @DateTime 2018-03-08
     *
     * @version  1.0
     *
     * @return [type] [description]
     */
    protected function combinData()
    {
        $server_ip = Input::get('ip');
        $server_name = Input::get('name');
        $server_id = Input::get('server_id');
        $server_port = Input::get('port');
        $server_desc = Input::get('desc');
        $s_regionName = Regional::find(Input::get('reg_id'))->name;
        $data_array = [
            'server_id' => intval($server_id),
            'server_name' => $server_name,
            'server_ip' => $server_ip,
            'server_port' => intval($server_port),
            'server_status' => intval(config('game.state')[5]),
            'server_desc' => $server_desc,
            'server_sign' => config('game.server_sign'),
            'region_name' => $s_regionName,
            'plat_limits' => '',
            'open_time' => 0,
        ];

        return $data_array;
    }

    /**
     * Edit interface.
     *
     * @param $id
     *
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header(trans('game.server_manger'));
            $content->description(trans('admin.edit'));
            $content->body($this->form()->edit($id));
        });
    }

    /**
     * [status serverlist表主键id修改服务器状态].
     *
     * @Author   王文凡
     * @DateTime 2018-03-09
     *
     * @version  1.0
     *
     * @param Request $request [description]
     *
     * @return
     */
    public function status(Request $request)
    {
        $this->validate($request, [
            'ids' => 'required',
        ]);
        $ids = Input::post('ids');
        $state = Input::post('state');

        foreach ($ids as $id) {
            $one = ServerList::withTrashed()->find($id);
            $ret = RequestService::changeState($one->server_id, $state);
            if (false == $ret) {
                return json_encode(['status' => 1, 'message' => trans('game.edit_fail').':'.$one->server_id]);
            }
            $one->status = $state;
            $one->save();
        }

        return json_encode(['status' => 0, 'message' => trans('game.edit_success')]);
    }

    /**
     * [ServerIdStatus 服务器id修改状态].
     *
     * @Author   王文凡
     * @DateTime 2018-03-10
     *
     * @version  1.0
     */
    public function ServerIdStatus()
    {
        $id = Input::post('id');
        $state = Input::post('state');
        $one = ServerList::withTrashed()->where('server_id', $id)->first();
        $game_state = config('game.state');
        if (null == $one) {
            return json_encode(['status' => 1, 'message' => trans('game.server_nonentity')]);
        }
        if (1 == $state) {
            //开服
            $one->status = $game_state[5];
            $one->save();
            ScriptService::startGame($id);
        } elseif (2 == $state) {
            if ($one->status != $game_state[5]) {
                return json_encode(['status' => 1, 'message' => trans('game.update_server_test')]);
            }
            //关服
            ScriptService::stopServer($id);
            $one->status = $game_state[3];
            $one->save();

            return json_encode(['status' => 0, 'message' => trans('game.close_success')]);
        } elseif (3 == $state) {
            //合服回收武器
            ScriptService::mergeWeapon($id);
        } elseif(4 == $state) {
            //重置首冲奖励
            RequestService::sendVip('19',$id);
        }

        return json_encode(['status' => 0, 'message' => trans('game.succeeded')]);
    }

    /**
     * [changePort 修改服务器端口].
     *
     * @Author   王文凡
     * @DateTime 2018-03-09
     *
     * @version  1.0
     *
     * @return [type] [description]
     */
    public function changePort(Request $request)
    {
        $this->validate($request, [
            'ids' => 'required',
        ]);
        $ids = Input::post('ids');
        $port = Input::post('port');
        foreach ($ids as $id) {
            //向服务器发送消息
            $one = ServerList::withTrashed()->find($id);
            if (null == $one) {
                Log::error(trans('game.port_not_exist').':', $id);
                continue;
            }
            $ret = RequestService::changePort($one->server_id, $port);
            if (false == $ret) {
                return json_encode(['status' => 1, 'message' => trans('game.edit_fail').':'.$one->server_id]);
            }
            $one->port = $port;
            $one->save();
        }

        return json_encode(['status' => 0, 'message' => trans('game.edit_success')]);
    }

    /**
     * [updateLocal 更新本地服务器表].
     *
     * @Author   王文凡
     * @DateTime 2018-03-09
     *
     * @version  1.0
     *
     * @param int   $s_id [服务器id]
     * @param array $data [description]
     *
     * @return [type] [description]
     */
    protected function updateLocal($s_id, $data)
    {
        $re = ServerList::where('server_id', $s_id)->update($data);
    }

    /**
     * [ServerStatus 服务器状态].
     *
     * @Author   王文凡
     * @DateTime 2018-03-09
     *
     * @version  1.0
     */
    public function ServerStatus()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('game.server_manger'));
            $content->description(trans('game.server_status'));
            $server = ServerList::all();
            $content->body(view('admin.server.status', ['server' => $server]));
        });
    }

    /**
     * [findStatus 查询服务器状态].
     *
     * @Author   王文凡
     * @DateTime 2018-03-10
     *
     * @version  1.0
     *
     * @return [type] [description]
     */
    public function findStatus()
    {
        $server_id = Input::get('server_id');
        if (empty(ServerOnlineService::serverExist($server_id))) {
            return json_encode(['status' => 1, 'message' => trans('game.server_null')]);
        }
        $info = ScriptService::grepServer($server_id);
        if (1 == $info) {
            return json_encode(['status' => 0, 'message' => trans('game.server_is_run')]);
        } elseif (2 == $info) {
            return json_encode(['status' => 0, 'message' => trans('game.server_is_op')]);
        } else {
            return json_encode(['status' => 0, 'message' => trans('game.server_is_close')]);
        }
    }
}




